<script setup lang="ts">
import { ref, watch } from 'vue'
import { useWebExtensionStorage } from '~/composables/useWebExtensionStorage'
import { useAuth } from '~/composables/useAuth'
import { ENV } from '~/env'
import { AuthenticatedApiClient } from '~/utils/api-auth'

const { data: channelId } = useWebExtensionStorage<string | null>('currentChannelId', null)

const {
  isAuthenticated,
  isLoginExpired,
  currentUser, // 用于模板显示
} = useAuth()

interface InfluencerData {
  id: string
  name: string
  subscriberCount: number
  videoCount: number
  viewCount: number
}

interface ReportItem {
  id: number
  type: string
  content: string
  severity_level: string
  processed_at: string | null
  created_at: string
  influencer: InfluencerData & { platform_user_id: string }
  user: { id: number, name: string }
}

const influencerData = ref<InfluencerData | null>(null)
const loading = ref(false)
const error = ref<string | null>(null)
const reports = ref<ReportItem[]>([])
const currentPage = ref(1)
const totalPages = ref(1)
const totalReports = ref(0)

async function fetchReports(id: string, page = 1) {
  if (!id)
    return

  loading.value = true
  error.value = null

  try {
    if (isLoginExpired.value) {
      error.value = '登录已过期，请重新登录'
      return
    }

    if (!isAuthenticated.value) {
      error.value = '请先登录后查看数据'
      return
    }

    const apiClient = new AuthenticatedApiClient(ENV.API_BASE_URL)
    const response = await apiClient.get(`/reports?platform_user_id=${encodeURIComponent(id)}&page=${page}`)
    const result = await response.json()
    if (!result.success)
      throw new Error('接口返回失败')

    const pageData = result.data

    reports.value = pageData.data
    currentPage.value = pageData.current_page
    totalPages.value = pageData.last_page
    totalReports.value = pageData.total

    // 从第一条举报中提取频道信息
    if (pageData.data.length > 0) {
      const info = pageData.data[0].influencer
      influencerData.value = {
        id: String(info.id),
        name: info.name,
        subscriberCount: info.follower_count || 0,
        videoCount: (info as any).videoCount || 0,
        viewCount: (info as any).viewCount || 0,
      }
    }
  }
  catch (e) {
    error.value = e instanceof Error ? e.message : '获取频道数据失败'
    reports.value = []
    influencerData.value = null
  }
  finally {
    loading.value = false
  }
}

// 打开登录页面
function openLoginPage() {
  const fullLoginUrl = `${ENV.LOGIN_DOMAIN}`
  window.open(fullLoginUrl, '_blank')
}

// eslint-disable @typescript-eslint/no-unused-vars, no-unused-vars
async function refreshReportList() {
  if (!channelId.value)
    return
  await fetchReports(channelId.value, currentPage.value)
}

// 监听 channelId 的变化
watch(channelId, (newId: string | null) => {
  if (newId && isAuthenticated.value && !isLoginExpired.value) {
    fetchReports(newId, 1)
  }
  else {
    influencerData.value = null
    reports.value = []
    currentPage.value = 1
    totalPages.value = 1
    totalReports.value = 0
  }
}, { immediate: true })

// 监听认证状态变化
watch([isAuthenticated, isLoginExpired], ([newAuthState, newExpiredState]) => {
  if (newAuthState && !newExpiredState && channelId.value) {
    // 登录状态恢复后，从第一页重新拉取数据并重置分页
    currentPage.value = 1
    fetchReports(channelId.value, 1)
  }
  else {
    // 退出登录或登录失效时，清空全部状态
    influencerData.value = null
    reports.value = []
    currentPage.value = 1
    totalPages.value = 1
    totalReports.value = 0
    error.value = null
  }
})

function nextPage() {
  if (currentPage.value < totalPages.value && channelId.value)
    fetchReports(channelId.value, currentPage.value + 1)
}

function prevPage() {
  if (currentPage.value > 1 && channelId.value)
    fetchReports(channelId.value, currentPage.value - 1)
}
</script>

<template>
  <main class="w-full px-4 py-5 text-center text-gray-700">
    <!-- 未登录状态或登录已过期 -->
    <div v-if="!isAuthenticated || isLoginExpired" class="auth-required">
      <div class="auth-card bg-white rounded-lg shadow-sm p-6 text-center">
        <div class="auth-icon mb-4">
          <div class="w-16 h-16 mx-auto bg-blue-100 rounded-full flex items-center justify-center">
            <svg class="w-8 h-8 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
            </svg>
          </div>
        </div>
        <h3 class="text-lg font-semibold mb-2">
          {{ isLoginExpired ? '登录已过期' : '需要登录' }}
        </h3>
        <p class="text-gray-600 mb-6">
          {{ isLoginExpired ? '您的登录已过期，请重新登录以查看数据' : '请登录您的账户以查看举报数据和频道信息' }}
        </p>
        <div class="space-y-3">
          <button
            class="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-md transition-colors duration-200"
            @click="openLoginPage"
          >
            {{ isLoginExpired ? '重新登录' : '前往登录' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 已登录且未过期状态 -->
    <div v-else-if="channelId">
      <!-- 用户信息显示 -->
      <div v-if="currentUser" class="user-info mb-4 text-right">
        <div class="flex items-center justify-end space-x-2">
          <span class="text-sm text-gray-500">当前账号:</span>
          <span class="text-sm font-medium">{{ currentUser.name || currentUser.email || '用户' }}</span>
          <div class="w-6 h-6 bg-green-500 rounded-full flex items-center justify-center">
            <svg class="w-3 h-3 text-white" fill="currentColor" viewBox="0 0 20 20">
              <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
            </svg>
          </div>
        </div>
      </div>

      <div v-if="loading" class="text-center py-4">
        <div class="flex items-center justify-center space-x-2">
          <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600" />
          <p>加载中...</p>
        </div>
      </div>

      <div v-else-if="error" class="text-center py-4">
        <div class="bg-red-50 border border-red-200 rounded-md p-4">
          <div class="flex items-center justify-center space-x-2 text-red-600">
            <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
              <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
            </svg>
            <span>{{ error }}</span>
          </div>
          <button
            class="mt-3 bg-red-600 hover:bg-red-700 text-white text-sm font-medium py-1 px-3 rounded-md transition-colors duration-200"
            @click="openLoginPage"
          >
            重试
          </button>
        </div>
      </div>

      <div v-else class="channel-info mb-6">
        <h2 class="text-lg font-semibold mb-4">
          频道信息
        </h2>
        <div class="space-y-2">
          <div class="channel-id text-sm text-gray-500">
            Channel ID: {{ channelId }}
          </div>
          <div v-if="influencerData" class="space-y-2">
            <!-- <div class="info-item">
              <span class="text-gray-500">频道名称：</span>
              <span class="font-medium">{{ influencerData.name }}</span>
            </div> -->
            <!-- <div class="info-item">
              <span class="text-gray-500">订阅数：</span>
              <span class="font-medium">{{ influencerData.subscriberCount.toLocaleString() }}</span>
            </div>
            <div class="info-item">
              <span class="text-gray-500">视频数：</span>
              <span class="font-medium">{{ influencerData.videoCount.toLocaleString() }}</span>
            </div>
            <div class="info-item">
              <span class="text-gray-500">总观看数：</span>
              <span class="font-medium">{{ influencerData.viewCount.toLocaleString() }}</span>
            </div> -->
          </div>
        </div>
      </div>

      <div class="report-list space-y-4">
        <div class="flex items-center justify-between mb-4">
          <h2 class="text-lg font-semibold">
            举报列表
          </h2>
          <div class="flex items-center gap-2">
            <button
              :disabled="loading"
              class="bg-gray-100 hover:bg-gray-200 text-gray-700 text-sm font-medium py-1 px-3 rounded-md transition-colors duration-200 disabled:opacity-50"
              @click="refreshReportList"
            >
              {{ loading ? '刷新中...' : '刷新' }}
            </button>
            <span class="text-sm text-gray-500">共 {{ totalReports }} 条举报</span>
          </div>
        </div>

        <template v-if="reports.length">
          <div
            v-for="report in reports"
            :key="report.id"
            class="report-card bg-white rounded-lg shadow-sm p-4 hover:shadow-md transition-shadow duration-200"
          >
            <div class="report-details space-y-2 text-left">
              <div class="report-item">
                <span class="text-sm text-gray-500">举报时间：</span>
                <span class="text-sm">{{ new Date(report.created_at).toLocaleString() }}</span>
              </div>
              <div class="report-item">
                <span class="text-sm text-gray-500">举报类型：</span>
                <span class="text-sm">{{ report.type }}</span>
              </div>
              <div class="report-description mt-3 p-3 bg-gray-50 rounded-md">
                <p class="text-sm text-gray-600">
                  举报详情：{{ report.content }}
                </p>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div class="flex justify-center items-center gap-4 mt-4">
            <button
              :disabled="currentPage === 1 || loading"
              class="px-3 py-1 text-sm rounded-md bg-gray-100 disabled:opacity-40"
              @click="prevPage"
            >
              上一页
            </button>
            <span class="text-sm text-gray-500">第 {{ currentPage }} / {{ totalPages }} 页</span>
            <button
              :disabled="currentPage === totalPages || loading"
              class="px-3 py-1 text-sm rounded-md bg-gray-100 disabled:opacity-40"
              @click="nextPage"
            >
              下一页
            </button>
          </div>
        </template>
        <p v-else class="text-sm text-gray-500 text-center">
          暂无举报数据
        </p>
      </div>
    </div>

    <!-- 已登录但无频道信息 -->
    <div v-else class="loading-state">
      <div class="text-center py-8">
        <div class="w-16 h-16 mx-auto bg-gray-100 rounded-full flex items-center justify-center mb-4">
          <svg class="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" />
          </svg>
        </div>
        <p class="text-gray-600">
          请先打开YouTube频道主页
        </p>
        <p class="text-sm text-gray-500 mt-2">
          在YouTube上访问任意频道页面即可查看相关信息
        </p>
      </div>
    </div>
  </main>
</template>

<style scoped>
.channel-info {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.channel-id {
  color: #666;
  font-size: 14px;
}

.loading-state {
  color: #666;
  font-style: italic;
}

.report-list {
  min-height: 200px;
}

.report-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.report-card:hover {
  cursor: pointer;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 8px;
  border-bottom: 1px solid #eee;
}

.info-item:last-child {
  border-bottom: none;
}
</style>
